package pile.pay.service.impl;

import pile.pay.entity.*;
import pile.pay.mapper.RechargeMapper;
import pile.pay.params.chargingGoldConfig.QueryDTO;
import pile.pay.params.recharge.RechargeDTO;
import pile.pay.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import pile.pay.utils.ToolsUtils;
import pile.pay.utils.WebUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import pile.pay.params.recharge.DeleDTO;
import pile.pay.params.recharge.ListDTO;
/**
 * <p>
 * 用户充值表 服务实现类
 * </p>
 *
 * @author 郭天义
 * @since 2024-06-28
 */
@Service
public class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements IRechargeService {

    @Autowired
    private RechargeMapper rechargeMapper;

    @Autowired
    private IElectricpileService electricpileService;

    @Autowired
    private IPlatformTrusteeshipService platformTrusteeshipService;

    @Autowired
    private IChargingGoldService chargingGoldService;

    @Autowired
    private IPowerStationService powerStationService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IBalanceChangeService balanceChangeService;

    @Autowired
    private IChargingGoldConfigService chargingGoldConfigService;

    @Autowired
    private IChargingGoldChangeService chargingGoldChangeService;

    @Autowired
    private IGrantPowerService grantPowerService;

    @Autowired
    private IGrantPowerRecordService grantPowerRecordService;

    @Autowired
    private IOccupyOrderService occupyOrderService;


    /**
     * 根据我们自己生成的 订单号 查询充值 信息 加锁  统一下单 支付回调调用
     * @param outTradeNo
     * @return
     */
    @Override
    public Recharge selectByRechargeOrderNoLock(String outTradeNo) {
        return  rechargeMapper.selectByRechargeOrderNoLock(outTradeNo);
    }

    @Override
    public ResponseResult<Recharge> rechargeNew(RechargeDTO rechargeDTO) {



        if (rechargeDTO.getRechargeAmount() == null) {
            return new ResponseResult(203, "请输入正确的充值金额");
        }
        if (rechargeDTO.getRechargeAmount().compareTo(new BigDecimal(0)) != 1) {
            return new ResponseResult(203, "请输入正确的充值金额");
        }
        //充值
        Recharge recharge = new Recharge();
        //获取用户信息
        recharge.setMemberId(rechargeDTO.getMemberId());
        recharge.setPaymentStatus(0);
        //充电金 入口  会有电站ID传过来
        recharge.setStationId(rechargeDTO.getStationId());
        //充值类型 0/余额 1/充电金
        recharge.setRechargeType(rechargeDTO.getRechargeType());
        recharge.setRechargeAmount(rechargeDTO.getRechargeAmount());
        //获取一个唯一订单号
        String rechargeOrderNo = ToolsUtils.uniqueId();
        recharge.setRechargeOrderNo(rechargeOrderNo);
        recharge.setChannel(rechargeDTO.getChannel());

        if (rechargeDTO.getRechargeType() == 0) {
            //现根据桩号查询出电桩
            Electricpile electricpile = electricpileService.selectByCode(rechargeDTO.getEquipmentCode());
            //根据电站id和渠道查询托管数据  获取商户号
            PlatformTrusteeship platformTrusteeship = platformTrusteeshipService.selectByStationIdAndChannel(electricpile.getStationId(),rechargeDTO.getChannel());

            //商户号
            String mchId = platformTrusteeship.getMchId();

            //充值余额
            recharge.setMchId(mchId);

            //电站ID
            recharge.setStationId(platformTrusteeship.getStationId());

        }
        if (rechargeDTO.getRechargeType() == 1) {
            PowerStation powerStation = powerStationService.getById(recharge.getStationId());
            //根据电站id和渠道查询托管数据  获取商户号
            PlatformTrusteeship platformTrusteeship = platformTrusteeshipService.selectByStationIdAndChannel(rechargeDTO.getStationId(),rechargeDTO.getChannel());


            //充电金充值
            recharge.setMchId(platformTrusteeship.getMchId());

            //获取用户在该电站之前的充电金余额
            ChargingGold chargingGold = chargingGoldService.selectByStationId(recharge.getStationId(), rechargeDTO.getMemberId(), rechargeDTO.getChannel());
            if (chargingGold == null) {
                ChargingGold chargingGoldNew = new ChargingGold();
                chargingGoldNew.setStationId(recharge.getStationId());
                chargingGoldNew.setMemberId(recharge.getMemberId());
                chargingGoldNew.setBalance(new BigDecimal(0));
                Member member = memberService.getById(recharge.getMemberId());
                if (member != null) {
                    chargingGoldNew.setPhone(member.getPhone());
                }
                if (powerStation != null) {
                    chargingGoldNew.setStationName(powerStation.getStationName());
                    chargingGoldNew.setAddress(powerStation.getAddress());
                }
                chargingGoldNew.setChannel(rechargeDTO.getChannel());
                chargingGoldService.add(chargingGoldNew);
            }
        }
        //生产充值数据
        rechargeMapper.insert(recharge);

        return new ResponseResult(200, recharge);

    }

    @Override
    public void rechargeCallbackProcessLogic(Recharge recharge) {


        //判断是什么类型的
        if (recharge.getRechargeType() == 0) {
            //余额支付
            //1 代表 已完成支付
            //分账状态 支付宝是不需要发分账的 所有支付宝服务调用的时候是赋值已分账的 ，其他两个就不需要赋值了直接默认未分账
            //支付状态
            recharge.setPaymentStatus(1);
            //支付时间
            recharge.setPaymentTime(new Date());

            //余额变动 会生成一条余额变动数据
            BalanceChange balanceChange = new BalanceChange();
            // 0 带表为收入
            balanceChange.setType(0);
            //获取用户信息
            balanceChange.setMemberId(recharge.getMemberId());
            // 变动前余额
            balanceChange.setBalanceBefore(new BigDecimal(0));
            //变动后的余额
            balanceChange.setBalanceAfter(new BigDecimal(0));
            //充值金额
            balanceChange.setAmount(recharge.getRechargeAmount());
            //场景的赋值
            balanceChange.setScene(0);
            //备注
            balanceChange.setRemarks("充值成功添加余额");
            //创建时间
            balanceChange.setCreateTime(new Date());
            //更新时间
            balanceChange.setUpdateTime(new Date());
            //渠道
            balanceChange.setChannel(recharge.getChannel());
            balanceChangeService.add(balanceChange);


        } else if (recharge.getRechargeType()==1) {
            //充电金支付
            //查询充电金配置
            QueryDTO queryDTO = new QueryDTO();
            queryDTO.setStationId(recharge.getStationId());
            queryDTO.setRechargeSatisfy(recharge.getRechargeAmount());
            //根据电站ID 和充值查询唯一一个充电金活动配置
            ChargingGoldConfig chargingGoldConfig = chargingGoldConfigService.selectGiveAwayAmount(queryDTO);
            //1 代表 已完成支付
            recharge.setPaymentStatus(1);
            //支付时间
            recharge.setPaymentTime(new Date());
            //赋值分账
            recharge.setLedgerAmount(new BigDecimal(0));
            //不需要分账 分账状态直接修改为分账成功
            recharge.setLedgerStatus(1);
            //退款状态
            recharge.setRefundStatus(1);
            //是否充电
            recharge.setIsCharge(1);
            //赠送金额
            recharge.setGiveAmount(chargingGoldConfig.getGiveAwayAmount());
            PlatformTrusteeship platformTrusteeship = platformTrusteeshipService.selectByStationIdAndChannel(recharge.getStationId(), recharge.getChannel());
            if (platformTrusteeship != null && platformTrusteeship.getIsTrusteeship() == 1){
                recharge.setIsSettlement(1);
            }
            //充电金变动 生成一条充电金变动数据
            ChargingGoldChange chargingGoldChange = new ChargingGoldChange();
            //0 代表收入
            chargingGoldChange.setType(0);
            //获取用户在该电站之前的充电金余额
            ChargingGold chargingGold = chargingGoldService.selectByStationId(recharge.getStationId(), recharge.getMemberId(), recharge.getChannel());


            //充电金余额
            BigDecimal memberBalance = recharge.getRechargeAmount().add(chargingGoldConfig.getGiveAwayAmount());

            //充电金余额修改   根据充电机余额表ID 修改余额 方法为 +  如果要扣除 直接金额取反
            chargingGoldService.updateBalanceById(memberBalance,chargingGold.getChargingGoldId());
            //变动之前的充电金
            chargingGoldChange.setBalanceBefore(chargingGold.getBalance());
            //变动后的余额
            chargingGoldChange.setBalanceAfter(chargingGold.getBalance().add(memberBalance));

            //充值金额
            chargingGoldChange.setAmount(memberBalance);
            //场景赋值
            chargingGoldChange.setScene(0);
            chargingGoldChange.setMemberId(recharge.getMemberId());
            chargingGoldChange.setStationId(recharge.getStationId());
            chargingGoldChange.setRemarks("充值" + chargingGoldConfig.getRechargeSatisfy() + "送" + chargingGoldConfig.getGiveAwayAmount());
            chargingGoldChange.setChannel(recharge.getChannel());
            chargingGoldChangeService.add(chargingGoldChange);

            //赠送免费电
            givePower(chargingGoldConfig, recharge.getMemberId(), recharge.getChannel());

        }else if (recharge.getRechargeType()==2) {

            //不需要分账 分账状态直接修改为分账成功
            recharge.setLedgerStatus(1);
            //1 代表 已完成支付
            recharge.setPaymentStatus(1);
            //支付时间
            recharge.setPaymentTime(new Date());
            //赋值分账
            recharge.setLedgerAmount(new BigDecimal(0));
            //退款状态
            recharge.setRefundStatus(1);
            //是否充电
            recharge.setIsCharge(1);
            PlatformTrusteeship platformTrusteeship = platformTrusteeshipService.selectByStationIdAndChannel(recharge.getStationId(),recharge.getChannel());
            if (platformTrusteeship != null && platformTrusteeship.getIsTrusteeship() == 1){
                recharge.setIsSettlement(1);
            }
            //修改占位订单状态
           //修改占位订单处理状态 1/已处理  根据我们自己生成的订单号查询占位订单
            List<OccupyOrder> occupyOrders = occupyOrderService.selectByPaymentOrderNumber(recharge.getRechargeOrderNo());
            if (occupyOrders == null || occupyOrders.size() == 0) {
                UpdateWrapper<OccupyOrder> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", 1);
                occupyOrderService.update(null, updateWrapper.in("member_id", recharge.getMemberId())
                        .eq("station_id", recharge.getStationId())
                        .eq("status", 2));
            } else {
                UpdateWrapper<OccupyOrder> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", 1);
                updateWrapper.set("payment_status", 2);
                occupyOrderService.update(null, updateWrapper.in("member_id", recharge.getMemberId())
                        .eq("station_id", recharge.getStationId())
                        .eq("status", 2)
                        .eq("payment_order_number", recharge.getRechargeOrderNo()));
            }

        }


        rechargeMapper.updateById(recharge);

        //查询是否有充电中的订单 发送新的余额给电桩
        electricpileService.updateChargingAccountBalance(recharge);
    }

    /**
     * 根据第三方支付单号查询 充值表数据
     * @param transactionId
     * @return
     */
    @Override
    public Recharge selectByTransactionIdLock(String transactionId) {
        Recharge recharge = rechargeMapper.selectByTransactionIdLock(transactionId);
        return recharge;
    }

    /**
     * 查询支付渠道是3,4的退款订单 sql if判断一下如果是3 就用in (3,4) if是2 就直接用 = 2
     * @param paymentChannel
     * @return
     */
    @Override
    public List<Recharge> selectByRemainingAmountByPaymentChannel(Integer paymentChannel) {
        List<Recharge> rechargeList = rechargeMapper.selectByRemainingAmountByPaymentChannel(paymentChannel);
        return rechargeList;
    }


    private void givePower(ChargingGoldConfig chargingGoldConfig, Integer memberId, Integer channel) {
        //判断充电金赠送配置赠送免费电是否是0
        if (chargingGoldConfig.getGivePower() == 0) {
            return;
        }
        //查询用户在该场站下的免费电量  根据电站ID 用户ID 渠道查询  免费电
        GrantPower grantPower = grantPowerService.selectByMemberIdAndStationId(memberId, chargingGoldConfig.getStationId(), channel);

        //修改用户免费电余额
        if (grantPower == null) {
            //没有数据添加一条新数据
            grantPower = new GrantPower();
            grantPower.setMemberId(memberId);
            grantPower.setStationId(chargingGoldConfig.getStationId());
            grantPower.setPower(new BigDecimal(chargingGoldConfig.getGivePower()));
            grantPowerService.add(grantPower);
        } else {
            //有数据的修改电量  根据免费电ID 修改免费电 +
            grantPowerService.updatePower(chargingGoldConfig.getGivePower(), grantPower.getGrantPowerId());
        }

        //生成领取电量记录
        GrantPowerRecord grantPowerRecord = new GrantPowerRecord();
        grantPowerRecord.setMemberId(memberId);
        grantPowerRecord.setStationId(chargingGoldConfig.getStationId());
        grantPowerRecord.setPower(new BigDecimal(chargingGoldConfig.getGivePower()));
        grantPowerRecord.setPowerBefore(grantPower.getPower().subtract(new BigDecimal(chargingGoldConfig.getGivePower())));
        grantPowerRecord.setPowerAfter(grantPower.getPower());
        grantPowerRecord.setRemarks("充值充电金赠送电量");
        grantPowerRecord.setType(1);
        grantPowerRecord.setChannel(channel);
        grantPowerRecordService.add(grantPowerRecord);
    }



}
